import {exec} from "node:child_process";
import {getAppPath, toggleWindowQuit} from "@/demos/ipc";
import log from "electron-log/renderer";
import {ElMessage, ElMessageBox, ElNotification} from "element-plus";
import {version} from "@/storage";
import {h} from "vue";
import {Session} from "@/utils/storage";

/**
 * 获取版本
 * @constructor
 */
export const GetUpdateVersion = (): Promise<string> => {
  return new Promise((resolve, reject) => {
    exec(`git ls-remote origin HEAD`, {}, (error, stdout) => {
      if (error) {
        log.info('获取git版本ID失败', error)
        reject(error)
      } else {
        const sp = stdout.split(/\t/)
        if (sp.length) resolve(sp[0].trim())
        else resolve('')
      }
    })
  })
}

/**
 * 获取更新日志
 * @constructor
 */
export const GetUpdateLog = (): Promise<string> => {
  return new Promise((resolve, reject) => {
    exec(`git log -1 --oneline`, {}, (error, stdout) => {
      if (error) {
        log.info('获取git版本ID失败', error)
        reject(error)
      } else {
        const sp = stdout.split(/\t/)
        if (sp.length) resolve(sp[0].trim())
        else resolve('')
      }
    })
  })
}

// /**
//  * 更新
//  * @constructor
//  */
// export const GetUpdateDeployer = (): Promise<string> => {
//   return new Promise((resolve, reject) => {
//     exec(`git pull`, {}, (error, stdout) => {
//       if (error) {
//         log.info('获取git版本ID失败', error)
//         reject(error)
//       } else {
//         resolve(stdout.trim())
//       }
//     })
//   })
// }

/**
 * 打开一个CMD用于更新
 * @constructor
 */
export const OpenCmdUpdate = async (): Promise<string> => {
  setTimeout(toggleWindowQuit, 300)
  const path = await getAppPath()
  const exePath = `${path}\\项目部署器.exe`
  return new Promise((resolve, reject) => {
    const cmd = `start "项目部署器更新进程" cmd /K "timeout /t 1 && git pull && timeout /t 1 && start "项目部署器" /b ${exePath} && exit"`
    exec(cmd, (error, stdout) => {
      if (error) {
        log.info('CMD更新失败', error)
        reject(error)
      } else {
        resolve(stdout.trim())
      }
    })
  })
}

/**
 * 查看需要更新不
 * @constructor
 */
export const onVersionMessageBox = async (ver?: string) => {
  if (!ver) ver = await GetUpdateVersion()
  if (ver === version.value) return ElMessage.warning('不需要更新')
  ElMessageBox.confirm(
    '即将关闭应用去更新，是否继续？',
    '更新提示',
    {
      confirmButtonText: '开始更新',
      cancelButtonText: '再等等',
      type: 'warning',
    }
  )
    .then(() => {
      version.value = ver
      OpenCmdUpdate().then(res => {
        console.log(res)
      })
    })
    .catch(() => {
      console.log('取消更新')
    })
}

/**
 * 检查是否需要更新，并打开更新提示窗口
 */
export const onOpenUpdate = async () => {
  const noNotification = Session.get('no-notification') || false
  if (!noNotification) {
    const ver = await GetUpdateVersion()
    if (version.value !== ver) {
      const log = await GetUpdateLog()
      const notification = ElNotification({
        title: '更新提示',
        message: h('div', {class: 'pa5 mt5 pre-wrap color-danger'}, [
          h('span', log || '有新的版本可以更新了，需要更新吗？'),
          h('div', {class: 'flex align-center justify-center mt10'}, [
            h('button', {
              class: 'el-button el-button--small ml10',
              onClick() {
                Session.set('no-notification', true)
                notification.close()
              }
            }, '下次再说'),
            h('button', {
              class: 'el-button el-button--primary el-button--small ml10',
              onClick() {
                onVersionMessageBox(ver)
                notification.close()
              }
            }, '马上更新'),
          ])
        ]),
        duration: 0,
        position: 'bottom-right'
      })
    }
  }

}


